<?php
namespace Common\Model;
class ChatRoomModel extends \Think\Model {
	
	protected $_validate = array (
		array ('chat_room_name', 'require', '聊天室名称不能为空', self::EXISTS_VALIDATE ), 
		array ('chat_room_name', '', '聊天室名称已存在', self::EXISTS_VALIDATE, 'unique' ) 
	);
	
	protected $_auto = array (
		array ('createtime', NOW_TIME, self::MODEL_INSERT ) 
	);
	
	public function _initialize() {
	
	}
	
	/**
	 * 根据条件获取聊天室数目
	 * @param array $where
	 */
	public function getCount($where = array()) {
		return $this->where ( $where )->count ();
	}
	
	/**
	 * 根据条件获取聊天室列表
	 * @param array $where
	 * @param string $order
	 * @param string $limit
	 */
	public function getList($where = array(), $order = 'id asc', $limit = '') {
		return $this->where ( $where )->order ( $order )->limit ( $limit )->select ();
	}
	
	/**
	 * 根据聊天室指定字段获取聊天室单条信息
	 * @param string $field
	 * @param string $value
	 */
	public function getRoom($field = 'id', $value) {
		$typeArray = array ('id', 'classifyid', 'chat_room_name' );
		if (in_array ( $field, $typeArray )) {
			$where [$field] = $value;
			return $this->where ( $where )->find ();
		} else {
			return false;
		}
	}
	
	/**
	 * 新增聊天室
	 * @param string $name
	 * @param array $info
	 */
	public function addRoom($name, $classifyid, $info = array()) {
		$data = array ('chat_room_name' => $name, 'classifyid' => $classifyid );
		if ($info) {
			$data = array_merge ( $data, $info );
		}
		if ($this->create ( $data )) {
			$res = $this->add ();
			return $res ? $res : 0;
		} else {
			return $this->getError ();
		}
	}
	
	/**
	 * 更新聊天室信息
	 * @param int $id
	 * @param array $data
	 */
	public function editRoom($id, $data) {
		if (empty ( $id ) || empty ( $data )) {
			$this->error = L ( 'error_parameter' );
			return false;
		}
		// 更新用户信息
		$data = $this->create ( $data );
		if ($data) {
			return $this->where ( array ('id' => $id ) )->save ( $data );
		}
		return $this->getError ();
	}
}